<template>
  <div class="auth-container">
    <div class="logo-area">
      <h2 class="title">AI 零代码应用生成平台</h2>
      <div class="subtitle">不写一行代码，生成完整应用</div>
    </div>

    <a-form
      ref="formRef"
      :model="formState"
      name="basic"
      autocomplete="off"
      @finish="handleSubmit"
      class="auth-form"
    >
      <!-- 账号输入框 -->
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input
          v-model:value="formState.userAccount"
          placeholder="请输入账号"
          autocomplete="username"
          class="form-input"
          size="large"
        >
          <template #prefix>
            <UserOutlined />
          </template>
        </a-input>
      </a-form-item>

      <!-- 密码输入框 -->
      <a-form-item
        :name="mode === 'login' ? 'userPassword' : 'userPassword'"
        :rules="passwordRules"
      >
        <a-input-password
          v-model:value="formState.userPassword"
          :placeholder="mode === 'login' ? '请输入密码' : '请设置密码'"
          :autocomplete="mode === 'login' ? 'current-password' : 'new-password'"
          class="form-input"
          size="large"
        >
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>

      <!-- 注册时的确认密码框 -->
      <a-form-item
        v-if="mode === 'register'"
        name="checkPassword"
        :rules="[
          { required: true, message: '请确认密码' },
          { min: 8, message: '密码不能小于 8 位' },
          { validator: validateCheckPassword },
        ]"
      >
        <a-input-password
          v-model:value="formState.checkPassword"
          placeholder="请确认密码"
          autocomplete="new-password"
          class="form-input"
          size="large"
        >
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>

      <!-- 底部提示信息 -->
      <div class="form-footer">
        <div class="tips">
          {{ mode === 'login' ? '没有账号？' : '已有账号？' }}
          <RouterLink :to="mode === 'login' ? '/user/register' : '/user/login'" class="auth-link">
            {{ mode === 'login' ? '去注册' : '去登录' }}
          </RouterLink>
        </div>
      </div>

      <!-- 提交按钮 -->
      <a-form-item>
        <a-button
          type="primary"
          size="large"
          html-type="submit"
          class="auth-button"
          :loading="loading"
          :disabled="loading"
        >
          <span v-if="!loading">{{ mode === 'login' ? '登录' : '注册' }}</span>
          <span v-else>处理中...</span>
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { LockOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { userLogin, userRegister } from '@/api/userController'
import { useLoginUserStore } from '@/stores/loginUser.ts'

// 定义组件属性
const props = defineProps({
  mode: {
    type: String,
    default: 'login', // 'login' 或 'register'
    validator: (value: string) => ['login', 'register'].includes(value),
  },
})

// 路由
const router = useRouter()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 表单状态
const formState = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
})

// 密码验证规则
const passwordRules = computed(() => [
  { required: true, message: '请输入密码' },
  { min: 8, message: '密码不能小于 8 位' },
])

// 验证确认密码（返回 Promise）
const validateCheckPassword = (_rule: unknown, value: string) => {
  return new Promise<void>((resolve, reject) => {
    if (value && value !== formState.userPassword) {
      reject(new Error('两次输入密码不一致'))
    } else {
      resolve()
    }
  })
}

// 提交表单
const handleSubmit = async (values: any) => {
  loading.value = true
  try {
    if (props.mode === 'login') {
      // 登录逻辑
      const res = await userLogin(values)
      if (res.data.code === 0 && res.data.data) {
        await useLoginUserStore().fetchLoginUser()
        message.success('登录成功')
        router.push({
          path: '/',
          replace: true,
        })
      } else {
        message.error('登录失败，' + res.data.message)
      }
    } else {
      // 注册逻辑
      const res = await userRegister(values)
      if (res.data.code === 0) {
        message.success('注册成功')
        router.push({
          path: '/user/login',
          replace: true,
        })
      } else {
        message.error('注册失败，' + res.data.message)
      }
    }
  } catch (error) {
    message.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 导出方法供父组件调用
defineExpose({
  handleSubmit,
  validateCheckPassword,
})
</script>

<style scoped>
/* 样式部分保持不变 */
.auth-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  padding: 48px 40px;
  width: 50%;
  min-width: 480px;
  max-width: 800px;
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
}

.auth-container:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 28px rgba(0, 0, 0, 0.12);
}

.logo-area {
  text-align: center;
  margin-bottom: 36px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.subtitle {
  color: #7f8c8d;
  font-size: 16px;
}

.auth-form {
  margin-top: 24px;
}

.form-input {
  margin-bottom: 5px;
}

.form-input :deep(.ant-input) {
  border-radius: 8px;
  padding: 14px 18px;
  border: 1px solid #e0e0e0;
  font-size: 15px;
  transition: all 0.3s;
}

.form-input :deep(.ant-input:hover),
.form-input :deep(.ant-input-focused) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-footer {
  margin-bottom: 24px;
}

.tips {
  text-align: right;
  color: #7f8c8d;
  font-size: 14px;
}

.auth-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.auth-link:hover {
  color: #40a9ff;
}

.auth-button {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: #1890ff;
  border: none;
  transition: all 0.3s;
}

.auth-button:hover {
  background: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(24, 144, 255, 0.3);
}

.auth-button:active {
  transform: translateY(0);
  box-shadow: none;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .auth-container {
    width: 60%;
    min-width: 400px;
  }
}

@media (max-width: 768px) {
  .auth-container {
    width: 80%;
    min-width: 320px;
    padding: 32px 24px;
  }

  .title {
    font-size: 24px;
  }

  .subtitle {
    font-size: 14px;
  }
}
</style>
